<template>
  <div id="FunctionModule">
    <vxe-toolbar perfect>
      <template #buttons>
        <div class="smallToolTitle">节点属性设置</div>
        <!-- <vxe-input clearable placeholder="关键字查询" class="vxeInputSearch" v-model="keywords" @search-click="search"
          @keyup="keyup" type="search"></vxe-input> -->

        <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading"
          @click="handleSearch"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建"
          @click="handleAdd('')"></vxe-button>
             <vxe-button type="text" class="button-red" icon="vxe-icon-delete" content="删除" @click="handleDelete"></vxe-button> -->
        <vxe-button type="text" icon="vxe-icon-save" content="保存" :loading="saveLoading" class="button-blue"
          @click="saveList"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="modulTable">
      <el-form ref="tableFieldFormRef" :model="tableFieldForm" class="form-input-m" label-width="90px" inline-message
        v-loading="tLoading">
        <!-- <el-row v-if="interfaceCode === 'bblzjm'"> -->
        <el-row>
          <el-col :span="7">
            <el-form-item label="是否有界面" label-width="135" prop="isInterface">
              <el-switch v-model="tableFieldForm.isInterface" inline-prompt active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" @change="switIsInterfaceCreatReceipt"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="assemblyName" label="选择界面" v-if="showInterface">
              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[
                { title: '名称', props: 'name' }, //列标题
                { title: '备注', props: 'bz' }
              ]" :placeholder="'选择界面'" :searchParam="{ code: 'BBLC' }" @selectDataRow="selectRow"
                @clearValue="genusCodeClear" v-model="tableFieldForm.assemblyName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="是否有标本退回功能" label-width="125" prop="processAttValue">
              <el-switch v-model="tableFieldForm.processAttValue" inline-prompt active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" @change="handleSwitchChange"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="assemblyName" label="选择功能" v-if="showProcessAttValue">
              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[
                { title: '编码', props: 'code' }, //列标题
                { title: '名称', props: 'name' }
              ]" :placeholder="'选择功能'" :searchParam="{ code: 'BBLCZJ' }" @selectDataRow="genusCodeSelect"
                @clearValue="genusCodeClear" v-model="tableFieldForm.assemblyName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="是否有生成交接单功能" label-width="135" prop="isCreatReceipt">
              <el-switch v-model="tableFieldForm.isCreatReceipt" inline-prompt active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" @change="switchChangeCreatReceipt"></el-switch>
            </el-form-item>
            <el-form-item label="是否有打印交接单功能" label-width="135" prop="isPrint">
              <el-switch v-model="tableFieldForm.isPrint" inline-prompt active-text="是" inactive-text="否" active-value="1"
                inactive-value="0" @change="switIsPrintCreatReceipt"></el-switch>
            </el-form-item>
            <el-form-item label="是否计费" label-width="135" prop="isBilling">
              <el-switch v-model="tableFieldForm.isBilling" inline-prompt active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" @change="switIsBillingCreatReceipt"></el-switch>
            </el-form-item>
            <el-form-item label="是否系统节点" label-width="135" prop="isSysAtt">
              <el-switch v-model="tableFieldForm.isSysAtt" inline-prompt active-text="是" inactive-text="否"
                active-value="1" inactive-value="0" @change="switIsSysAttCreatReceipt"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
// import MenuList from './MenuList.vue';
import Breadcrumb from '../../../components/Breadcrumb.vue';
import VxePulldownSelection from '../../../components/VxePulldownSelection.vue';
import VxePulldownSelectIconfont from '../../../components/VxePulldownSelectIconfont.vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import SelectDataList from '@/components/SelectDataList.vue';
let store = AppStore();
let { proxy }: any = getCurrentInstance();
//暴露属性和方法
defineExpose({
  initPage
});

// 设计模式 最右侧表单
let tableFieldForm = reactive({
  //id: '',
  processAttValue: '',//是否有标本退回功能
  assemblyName: '',
  assemblyValue: '',
  nodeName: '',
  processSetId: '',
  isCreatReceipt: '',//是否有生成交接单功能
  isPrint: '',//是否有打印交接单功能
  isInterface: '',//是否有界面
  isBilling: '',//是否计费
  isSysAtt: '' //是否系统节点
});
let tLoading = ref(false);
// 页面标题
let content = ref('不合格记录原因');
// 用户输入关键字
let keywords = ref('');

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存

//**判断为空*/
let IsEmpty = (value: any) => {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
};
let processAttributeList: any = reactive([]);

let processSetId = '';
let nodeName = '';
let showInterface = ref(false);
let showProcessAttValue = ref(false);
let interfaceCode = ref('');

onMounted(() => {
  getprocessAttributeList();
});


function initPage(rowData: any) {
  processSetId = rowData.id;
  tableFieldForm.processSetId = rowData.id;
  interfaceCode.value = rowData.interfaceCode;
  tableFieldForm.nodeName = rowData.nodeName;
  nodeName = rowData.nodeName;
  getprocessAttributeList();
}

//选择功能
function genusCodeSelect(row) {
  tableFieldForm.assemblyValue = row.value;
  tableFieldForm.assemblyName = row.name;
}
//清空功能
function genusCodeClear() {
  tableFieldForm.assemblyValue = '';
  tableFieldForm.assemblyName = '';
}

//选择界面
function selectRow(row) {
  console.log('组件点击---', row);

}

//清空界面
function clearRow(row) {
  console.log('组件点击---', row);
  
}

function handleSwitchChange(val) {
  if (val === '1') {
    showProcessAttValue.value = true;
  } else if (val === '0') {
    showProcessAttValue.value = false;
  }
}
function switchChangeCreatReceipt(val) {//暂无业务逻辑
  // console.log('---------------val.value----',val);
  // //设置tableFieldForm值
  // tableFieldForm.processAttValueList.add(val)
  // console.log('tableFieldForm.processAttValueList',tableFieldForm.processAttValueList);
}

function switIsPrintCreatReceipt() {//暂无业务逻辑

}

function switIsInterfaceCreatReceipt(val) {//暂无业务逻辑
  if (val === '1') {
    showInterface.value = true;
  } else if (val === '0') {
    showInterface.value = false;
  }
}

function switIsBillingCreatReceipt() {//暂无业务逻辑

}

function switIsSysAttCreatReceipt() {//暂无业务逻辑

}

function cleanForm() {
  for (const key of Object.keys(tableFieldForm)) {
    if (key === 'processSetId' || key === 'nodeName') {
      break;
    }
    tableFieldForm[key] = '';
  }
  showProcessAttValue.value = false;
}
// 请求表格数据
function getprocessAttributeList() {
  cleanForm();
  showLoading.value = true;
  processAttributeList.length = 0; //放入数据前清空数组
  proxy.$http
    .get('/lab/process/attribute/getProcessAttributeList', {
      params: { keywords: keywords.value, processSetId: processSetId }
    })
    .then((res: any) => {
      if (res.status.code === 200) {
        showLoading.value = false;
        // console.log('模块数据列表', res.status.code);
        processAttributeList.push(...res.data);
        // 判断 processAttributeList 数组中是否存在 processAttValue 为 0 的元素,有则设置界面中的退回按钮为是
        const hasZeroValue = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '0');
        if (hasZeroValue) {
          tableFieldForm.processAttValue = '1';
          const filteredItems0 = processAttributeList.filter(
            (item) => item.processAttValue === '1' && item.isAssembly === '0'
          );
          // tableFieldForm.id = filteredItems0[0].id;
          const filteredItems = processAttributeList.filter(
            (item) => filteredItems0[0].id === item.parentId
          );
          showProcessAttValue.value = true;
          tableFieldForm.assemblyName = filteredItems[0].processAttName;
          tableFieldForm.assemblyValue = filteredItems[0].processAttValue;
        }
        const hasZeroValue2 = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '1');
        if (hasZeroValue2) {
          tableFieldForm.isCreatReceipt = '1'
        } else {
          tableFieldForm.isCreatReceipt = '0'
        }
        const hasZeroValue3 = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '2');
        if (hasZeroValue3) {
          tableFieldForm.isPrint = '1'
        } else {
          tableFieldForm.isPrint = '0'
        }
        const hasZeroValue4 = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '3');
        if (hasZeroValue4) {
          tableFieldForm.isInterface = '1'
        } else {
          tableFieldForm.isInterface = '0'
        }
        const hasZeroValue5 = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '4');
        if (hasZeroValue5) {
          tableFieldForm.isBilling = '1'
        } else {
          tableFieldForm.isBilling = '0'
        }
        const hasZeroValue6 = processAttributeList.some((item) => item.processAttValue === '1' && item.isAssembly === '5');
        if (hasZeroValue6) {
          tableFieldForm.isSysAtt = '1'
        } else {
          tableFieldForm.isSysAtt = '0'
        }

      } else {
        VXETable.modal.message({ content: res.status.msg, status: 'error' });
        return;
      }
    });
}

// 保存节点属性
function saveList(callback: any) {
  // if (tableFieldForm.isCreatReceipt === '1' && IsEmpty(tableFieldForm.processAttValue)) {
  //   VxeMessage('请选择属性', VxeNotifyType.error);
  //   return
  // }
  const url = '/lab/process/attribute/addProcessAttribute';
  proxy.$http
    .post(url, tableFieldForm)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        if (callback) {
          callback(true);
        }
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
        if (callback) {
          callback(false);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage('保存异常', VxeNotifyType.error);
      // if (callback) {
      //   callback(false);
      // }
    });
}

// 当前选中行的下标
// let clickIndex = null;
// 点击行
// function moduleRowClick({ row, rowIndex }) {
//   clickIndex = rowIndex;
//   let $Xtable = proxy.$refs.unqualifiedTable;
//   $Xtable.setCurrentRow(row);
// }
// 点击刷新
// function handleSearch() {
//   getprocessAttributeList();
// }
//let unqualifiedTable = ref();
// // 点击新增
// async function handleAdd(row: any) {
//   if (IsEmpty(processSetId)) {
//     VxeMessage('请选中左侧列表节点', VxeNotifyType.warning);
//   }
//   const record = {
//     id: '',
//     processSetId: processSetId,
//     processAttName: '',
//     processAttCode: '',
//     seq: processAttributeList.length + 1, //排序号
//     nodeName: nodeName
//   };
//   processAttributeList.push(record);
// }

// 点击删除
// async function handleDelete() {
//   let $Xtable = proxy.$refs.unqualifiedTable;
//   let selectRows = $Xtable.getCheckboxRecords();
//   let ids = '';
//   let names = '';
//   // const data = {ids:'',names:''};

//   if (selectRows <= 0) {
//     VxeMessage('请勾选要删除的数据', VxeNotifyType.warning);
//     return;
//   } else {
//     selectRows.forEach((row) => {
//       // 对每一行执行特定操作
//       console.log('row-----------', row);
//       ids += row.id + ',';
//       names += row.reason + ',';

//       // 其他操作...
//     });
//     // 去掉最后一个逗号
//     ids = ids.slice(0, -1);
//     names = names.slice(0, -1);
//     let data = { ids: ids, names: names, name: nodeName};
//     proxy
//       .$confirm('确定删除此条用户数据？', '提示', {
//         cancelButtonClass: 'cancel-button',
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       })
//       .then(() => {
//         proxy.$http
//           .post('/lab/process/attribute/daleteProcessAttribute/', data)
//           .then((res: any) => {
//             if (res.status.code === 400) {
//               VxeMessage('删除成功', VxeNotifyType.success);
//               getprocessAttributeList();
//             } else {
//               VxeMessage('删除失败', VxeNotifyType.error);
//             }
//           })
//           .catch((err: any) => {
//             VxeMessage('删除异常', VxeNotifyType.error);
//           });
//       });
//   }
// }

// 点击修改保存
// async function saveList() {
//   saveLoading.value = true;
//   // 获取表格实例
//   let $Xtable = proxy.$refs.unqualifiedTable;
//   if ($Xtable) {
//     // 表格实例表用该方法拿到有id的为修改
//     const updateList = await $Xtable.getUpdateRecords().filter((p: any) => {
//       return p.id !== '';
//     });
//     // 拿到数组中没有id的数据为新增
//     const InsertList = processAttributeList.filter((e: any) => {
//       return e.id === '';
//     });
//     // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
//     let processAttName = '';
//     if (updateList.length > 0) {
//       updateList.forEach((record) => {
//         processAttName += record.processAttName + ',';
//       });
//       processAttName = processAttName.slice(0, -1);
//       const reqData = { labProcessAttributes: updateList, processAttName: processAttName, nodeName:nodeName };
//       proxy.$http
//         .post('/lab/process/attribute/updateProcessAttribute', reqData)
//         .then((res: any) => {
//           if (res.status.code === 400) {
//             VxeMessage('修改成功', VxeNotifyType.success);
//           }
//         })
//         .catch((err: any) => {
//           VxeMessage('修改异常', VxeNotifyType.error);
//         });
//     }
//     let AddProcessAttName = '';
//     if (InsertList.length > 0) {
//       InsertList.forEach((record) => {
//         AddProcessAttName += record.processAttName + ',';
//       });
//       AddProcessAttName = AddProcessAttName.slice(0, -1);
//       const reqData = { labProcessAttributes: InsertList, processAttName: AddProcessAttName ,nodeName:nodeName};
//       proxy.$http
//         .post('/lab/process/attribute/addProcessAttribute', reqData)
//         .then((res: any) => {
//           if (res.status.code === 400) {
//             VxeMessage('新增成功', VxeNotifyType.success);
//           }
//         })
//         .catch((err: any) => {
//           VxeMessage('新增异常', VxeNotifyType.error);
//         });
//     }
//     setTimeout(() => {
//       getprocessAttributeList();
//       saveLoading.value = false;
//     }, 500);
//   } else {
//     return;
//   }
// }

// 关键字搜索
function search() {
  getprocessAttributeList();
}

function keyup(e: any) {
  if (e.$event.code == 'Enter') {
    search();
  }
}
</script>
<style lang="scss" scoped>
#FunctionModule {
  height: 100%;
  width: 100%;

  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }

  // 左边表格
  .modulTable {
    height: calc(100% - 40px);
    padding: 10px;
    background-color: $base-white;
  }
}
</style>
